// pages/cart/index.js
import { requestPayment } from '../../lib/asyncWx/asyncWx.js';
import { request } from '../../request/index.js';
const regeneratorRuntime = require('../../lib/runtime/runtime.js');
// 全选和反选功能
// 1. 先绑定事件
// 2. 获取cartList中的check
Page({

  /**
   * 页面的初始数据
   */
  data: {
    address: {},
    cart: [], // 购物车中的商品信息
    totalNum: 0,
    totalPrice: 0,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

  },
  // 显示用户地址
  onShow() {
    // 从缓存中获取地址
    const address = wx.getStorageSync('address');
    // 获取购物车的商品信息
    let cart = wx.getStorageSync('cartList') || [];
    // 过滤购物车数组
    cart = cart.filter(item => item.check);
    this.setData({
      address,
    });
    // 1 总价格 总数量
    let totalPrice = 0;
    let totalNum = 0;
    cart.forEach(v => {
      totalPrice += v.num * v.goods_price;
      totalNum += v.num;
    })
    this.setData({
      cart,
      totalPrice, totalNum
    });;
  },
  async handleOrderPay() {
    let { address, cart, totalPrice, totalNum } = this.data;
    // 判断是否有token
    const token = wx.getStorageSync('token');
    if (!token) {
      // 跳转
      wx.navigateTo({
        url: '/pages/auth/index',
      })
      return;
    };
    // 存在token
    // 创建订单
    // 请求头
    const header = { Authorization: token };
    // 参数
    let order_price = totalPrice;
    let consignee_addr = address.all;
    let goods = [];
    cart.forEach(item => goods.push({
      goods_id: item.goods_id,
      goods_number: item.num,
      goods_price: item.goods_price,
    }));
    let params = {
      order_price,
      consignee_addr,
      goods,
    }
    // 创建订单编号
    let { order_number } = await request({ url: '/my/orders/create', header: header, data: params, method: 'POST' });
    console.log(order_number);
    // 发起预支付
    let { pay } = await request({ url: '/my/orders/req_unifiedorder', header: header, data: { order_number }, method: 'POST' });
    console.log(res);
    // let { nonceStr, package, paySign, signType, timeStamp } = res.pay;
    // 微信支付API
    console.log('pay', pay);
    const res = await requestPayment(pay).catch(err => {
      console.log(err);
    });
    console.log(res);
  }
})